package com.jingdianjichi.club.wx.controller;

import com.jingdianjichi.club.wx.handlers.WxChatMessageHandler;
import com.jingdianjichi.club.wx.handlers.WxChatMsgFactory;
import com.jingdianjichi.club.wx.utils.MessageUtil;
import com.jingdianjichi.club.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;


/**
 * @author 86156
 * @version 1.0
 * @date 2024-11-04 11:59
 */
@RestController
@Slf4j
public class CallBackController {

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    private String token = "zuiacsn";

    @GetMapping("test")
    public String test(){
        return "test";
    }

    @GetMapping("callback")
    public String callBack(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echoStr){
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echoStr);
        String sha1 = SHA1.getSHA1(token, timestamp, nonce,"");
        if (signature.equals(sha1)) {
            return echoStr;
        }
        return "unknown";
    }

    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信消息：requestBody：{}", requestBody);
        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        String msgType = messageMap.get("MsgType");
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if(!StringUtils.isEmpty(event)){
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        WxChatMessageHandler handler = wxChatMsgFactory.getHandler(msgTypeKey);
        String replayContent = handler.dealMsg(messageMap);
        log.info("replayContent:{}", replayContent);
        return replayContent;
    }

}
